﻿<template>
  <div class="jnpf-content-wrapper">
    <div class="jnpf-content-wrapper-center">
      <div class="jnpf-content-wrapper-search-box">
        <BasicForm @register="registerSearchForm" :schemas="searchSchemas" @advanced-change="redoHeight" @submit="handleSearchSubmit" @reset="handleSearchReset" class="search-form">
        </BasicForm>
      </div>
      <div class="jnpf-content-wrapper-content">
        <BasicTable @register="registerTable" v-bind="getTableBindValue" ref="tableRef" @columns-change="handleColumnChange">
          <template #tableTitle>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action' && !record.top">
              <TableAction :actions="getTableActions(record)" />
            </template>
          </template>
        </BasicTable>
      </div>
    </div>
    <Form ref="formRef" @reload="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { getList, del, exportData, batchDelete } from './helper/api';
  import { getDictionaryDataSelector } from '/@/api/systemData/dictionary';
  import { getDataInterfaceRes } from '/@/api/systemData/dataInterface';
  import { ref, reactive, onMounted, toRefs, computed, unref, nextTick } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useOrganizeStore } from '/@/store/modules/organize';
  import { useUserStore } from '/@/store/modules/user';
  import { useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicTable, useTable, TableAction, ActionItem, TableActionType } from '/@/components/Table';
  import Form from './Form.vue';
  import { ExportModal, ImportModal, SuperQueryModal } from '/@/components/CommonModal';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useRoute } from 'vue-router';
  import { FilterOutlined } from '@ant-design/icons-vue';
  import { getSearchFormSchemas } from '/@/components/FormGenerator/src/helper/transform';
  import { cloneDeep } from 'lodash-es';
  import columnList from './helper/columnList';
  import searchList from './helper/searchList';
  import { dyOptionsList } from '/@/components/FormGenerator/src/helper/config';
  import { thousandsFormat } from '/@/utils/jnpf';
  interface State {
    config: any;
    columnList: any[];
    printListOptions: any[];
    columnBtnsList: any[];
    customBtnsList: any[];
    treeActiveId: string;
    treeActiveNodePath: any;
    columns: any[];
    complexColumns: any[];
    childColumnList: any[];
    exportList: any[];
    cacheList: any[];
    currFlow: any;
    isCustomCopy: boolean;
    candidateType: number;
    currRow: any;
    workFlowFormData: any;
    expandObj: any;
    columnSettingList: any[];
    searchSchemas: any[];
    treeRelationObj: any;
    treeQueryJson: any;
  }

  const route = useRoute();
  const { createMessage, createConfirm } = useMessage();
  const { t } = useI18n();
  const organizeStore = useOrganizeStore();
  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo;

  const [registerExportModal, { openModal: openExportModal, closeModal: closeExportModal, setModalProps: setExportModalProps }] = useModal();
  const [registerImportModal, { openModal: openImportModal }] = useModal();
  const [registerSuperQueryModal, { openModal: openSuperQuery }] = useModal();
  const formRef = ref<any>(null);
  const tableRef = ref<Nullable<TableActionType>>(null);
  const detailRef = ref<any>(null);
  const defaultSearchInfo = {
    menuId: route.meta.modelId as string,
    moduleId:'521647080423292869',
    superQueryJson: '',
  };
  const searchInfo:any = reactive({
    ...cloneDeep(defaultSearchInfo),
  });
  const state = reactive<State>({
    config: {},
    columnList: [],
    printListOptions: [],
    columnBtnsList: [],
    customBtnsList: [],
    treeActiveId: '',
    treeActiveNodePath: [],
    columns: [],
    complexColumns: [], // 复杂表头
    childColumnList: [],
    exportList: [],
    cacheList: [],
    currFlow: {},
    isCustomCopy: false,
    candidateType: 1,
    currRow: {},
    workFlowFormData: {},
    expandObj: {},
    columnSettingList: [],
    searchSchemas: [],
    treeRelationObj: null,
    treeQueryJson: {},
  });
  const { childColumnList, searchSchemas } = toRefs(state);
  const [registerSearchForm, { updateSchema, submit: searchFormSubmit }] = useForm({
    baseColProps: { span: 6 },
    showActionButtonGroup: true,
    showAdvancedButton: true,
    compact: true,
  });
  const [registerTable, { reload, setLoading, getFetchParams, getSelectRowKeys, redoHeight, clearSelectedRowKeys }] = useTable({
    api: getList,
    immediate: false,
    clickToRowSelect: false,
    afterFetch: (data) => {
      const list = data.map((o) => ({
        ...o,
        ...state.expandObj,
      }));
      state.cacheList = cloneDeep(list);
      return list;
    },
  });

  const getTableBindValue = computed(() => {
    let columns = state.complexColumns;
    const data: any = {
      pagination: false, //没有分页，树形，分组
      searchInfo: unref(searchInfo),
      defSort: {
        sort: 'desc', //sort
        sidx: '', //取defaultSidx
      },
      columns,
      bordered: true,
      actionColumn: {
        width: 150,
        title: '操作',
        dataIndex: 'action',
      },
    };
    return data;
  });
function getTableActions(record): ActionItem[] {
  return [
    {
      label: '编辑',
      onClick: updateHandle.bind(null, record),
    },
  ];
}
  // 编辑
  function updateHandle(record) {
    // 不带工作流
    const data = {
      id: record.id,
      menuId: searchInfo.menuId,
      allList: state.cacheList,
    };
    formRef.value?.init(data);
  }
  function init() {
    state.config = {};
    searchInfo.menuId = route.meta.modelId as string;

    state.columnList = columnList;

    setLoading(true);
    getSearchSchemas();
    getColumnList();
    nextTick(() => {
      // 有搜索列表
      searchFormSubmit();
    });
  }
  function getSearchSchemas() {
    const schemas = getSearchFormSchemas(searchList);
    state.searchSchemas = schemas;
    schemas.forEach((cur) => {
      const config = cur.__config__;
      if (dyOptionsList.includes(config.jnpfKey)) {
        if (config.dataType === 'dictionary') {
          if (!config.dictionaryType) return;
          getDictionaryDataSelector(config.dictionaryType).then((res) => {
            updateSchema([{ field: cur.field, componentProps: { options: res.data.list } }]);
          });
        }
        if (config.dataType === 'dynamic') {
          if (!config.propsUrl) return;
          const query = { paramList: config.templateJson || [] };
          getDataInterfaceRes(config.propsUrl, query).then((res) => {
            const data = Array.isArray(res.data) ? res.data : [];
            updateSchema([{ field: cur.field, componentProps: { options: data } }]);
          });
        }
      }
      cur.defaultValue = cur.value;
    });
  }
  function getColumnList() {
    // 没有权限
    let  columnList = state.columnList;

  state.exportList = columnList;
  let columns = columnList.map((o) => ({
    ...o,
    title: o.label,
    dataIndex: o.prop,
    align: o.align,
    fixed: o.fixed == 'none' ? false : o.fixed,
    sorter: o.sortable,
    width: o.width || 100,
  }));
    columns = getComplexColumns(columns);
  state.columns = columns.filter((o) => o.prop.indexOf('-') < 0);
  getChildComplexColumns(columns);
}
  function getComplexColumns(columns) {
    let complexHeaderList: any[] = [];
    if (!complexHeaderList.length) return columns;
    let childColumns: any[] = [];
    for (let i = 0; i < complexHeaderList.length; i++) {
      const e = complexHeaderList[i];
      e.title = e.fullName;
      e.align = e.align;
      e.dataIndex = e.id;
      e.prop = e.id;
      e.children = [];
      e.jnpfKey = 'complexHeader';
      if (e.childColumns?.length) {
        childColumns.push(...e.childColumns);
        for (let k = 0; k < e.childColumns.length; k++) {
          const item = e.childColumns[k];
          for (let j = 0; j < columns.length; j++) {
            const o = columns[j];
            if (o.__vModel__ == item && o.fixed !== 'left' && o.fixed !== 'right' && !o.__config__.isSubTable) e.children.push({ ...o });
          }
        }
      }
    }
    complexHeaderList = complexHeaderList.filter(o => o.children.length);
    for (let i = 0; i < columns.length; i++) {
      const item = columns[i];
      if (!childColumns.includes(item.__vModel__) || item.__config__.isSubTable) complexHeaderList.push(item);
    }
    return complexHeaderList;
  }
  function getChildComplexColumns(columnList) {
    let list: any[] = [];
    for (let i = 0; i < columnList.length; i++) {
      const e = columnList[i];
      if (!e.prop.includes('-')) {
        list.push(e);
      } else {
        let prop = e.prop.split('-')[0];
        let vModel = e.prop.split('-')[1];
        let label = e.label.split('-')[0];
        let childLabel = e.label.replace(label + '-', '');
        let newItem = {
          align: 'center',
          jnpfKey: 'table',
          prop,
          label,
          title: label,
          dataIndex: prop,
          children: [],
        };
        e.dataIndex = vModel;
        e.title = childLabel;
        if (!state.expandObj.hasOwnProperty(`${prop}Expand`)) state.expandObj[`${prop}Expand`] = false;
        if (!list.some((o) => o.prop === prop)) list.push(newItem);
        for (let i = 0; i < list.length; i++) {
          if (list[i].prop === prop) {
            list[i].children.push(e);
            break;
          }
        }
      }
    }
    // 行内分组展示
    getMergeList(list);
    state.complexColumns = list;
    state.childColumnList = list.filter((o) => o.jnpfKey === 'table');
    // 子表分组展示宽度取100
    for (let i = 0; i < state.childColumnList.length; i++) {
      const e = state.childColumnList[i];
      if (e.children?.length) e.children = e.children.map(o => ({ ...o, width: 100 }));
    }
  }
  function getMergeList(list) {
    list.forEach((item) => {
      if (item.jnpfKey === 'table' && item.children && item.children.length) {
        item.children.forEach((child, index) => {
          if (index == 0) {
            child.customCell = () => ({
              rowspan: 1,
              colspan: item.children.length,
              class: 'child-table-box',
            });
          } else {
            child.customCell = () => ({
              rowspan: 0,
              colspan: 0,
            });
          }
        });
      }
    });
  }
  function handleColumnChange(data) {
    state.columnSettingList = data;
  }
  function handleSearchReset() {
    searchFormSubmit();
  }
  function handleSearchSubmit(data) {
    clearSelectedRowKeys();
    let obj = {
      ...defaultSearchInfo,
      superQueryJson: searchInfo.superQueryJson,
      ...data,
      ...(state.treeQueryJson || {})
    };
    Object.keys(searchInfo).map(key => {
      delete searchInfo[key];
    });
    for (let [key, value] of Object.entries(obj)) {
      //searchInfo[key.replaceAll('-', '_')] = value;
    }
    reload({ page: 1 });
  }
  onMounted(() => {
    init();
  });
</script>
